package sv.net;

import java.io.*;
import java.net.*;


public class NetworkIOServer extends Thread {

	private NetworkIO connection = null;
	InputStream input;
	OutputStream output;
	boolean running = true;
	
	
	NetworkIOServer(NetworkIO pConnection) {
		this.connection = pConnection;
		this.running = true;
	}
	
	
	public void run() {
		ServerSocket server = null;
		try {
			server = new ServerSocket(NetworkIO.port);
		} catch (IOException e) {
			System.out.println("argl");
		}
		while (running) {
			try {
				Socket client = server.accept();
				input = client.getInputStream();
				output = client.getOutputStream();
				
				int command = input.read();
				int field = -1;
				while (command != -1) {
					field = input.read();
					output.write(NetworkIO.MSG_RECEIVED);
					output.flush();
					connection.message(command,field);
					command = input.read();
				}
				
				input.close();
				output.close();
			} catch (IOException e) {}
		}
		try {
			server.close();
		} catch (IOException e) {}
	}
	
	
	synchronized int send(int command, int field) {
		try {
			output.write(command);
			output.write(field);
			output.flush();
			return input.read();
		} catch (IOException e) {
			return -2;
		}
	}


}
